package xmlTools;

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class XMLUtil {
    private String fileRoute;

    private static class ErrDocmException extends Exception {
        public String getMessage() {
            // TODO Auto-generated method stub
            return "无法创建Document！";
        }
    }

    private static class ErrNodeValueException extends Exception {
        public String getMessage() {
            // TODO Auto-generated method stub
            return "无法获取该NodeValue！";
        }
    }

    public XMLUtil(String fileRoute) {
        this.fileRoute = fileRoute;
    }

    public String getFirstNodeValue(String nodeName) throws ErrNodeValueException {
        try {
            Document document = this.getDocument(this.fileRoute);
            // 获取包含类名的文本节点
            NodeList nodeList = document.getElementsByTagName(nodeName);
            Node node = nodeList.item(0).getFirstChild();
            String nodeValue = node.getNodeValue();
            return nodeValue;
        } catch (Exception e) {
            e.printStackTrace();
        }
        throw new ErrNodeValueException();
    }

    private Document getDocument(String file) throws ErrDocmException {
        // 创建DOM文档对象
        DocumentBuilderFactory documentBuilderFactory;
        DocumentBuilder documentBuilder;
        Document document;
        try {
            documentBuilderFactory = DocumentBuilderFactory.newInstance();
            documentBuilder = documentBuilderFactory.newDocumentBuilder();
            document = documentBuilder.parse(new File(file));
            return document;
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        throw new ErrDocmException();
    }
}
